package handler

import (
	"github/casperkwok/shortener/internal/model"
	"math/rand"
	"net/http"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

// 生成随机短码
func GenerateShortCode(n int) string {
	letters := []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
	b := make([]rune, n)
	for i := range b {
		b[i] = letters[rand.Intn(len(letters))]
	}
	return string(b)
}

func ShortenURL(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		var req struct {
			URL string `json:"url"`
		}
		if err := c.BindJSON(&req); err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"error": "请求格式错误"})
			return
		}
		// 生成短码（6位）
		code := GenerateShortCode(6)

		// 存入数据库
		newURL := model.URL{Code: code, Long: req.URL}
		db.Create(&newURL)

		//返回短链
		c.JSON(http.StatusOK, gin.H{"short_url": "/" + code})

	}
}

func RedirectURL(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		code := c.Param("code")
		var url model.URL
		if err := db.First(&url, "code = ?", code).Error; err != nil {
			c.JSON(http.StatusNotFound, gin.H{"error": "短链接不存在"})
			return
		}
		// 302 重定向
		c.Redirect(http.StatusFound, url.Long)
	}
}
